package info.douyi.dps.controller;

import info.douyi.dps.model.*;
import info.douyi.dps.model.DTO.req.PestInsertRequestDTO;
import info.douyi.dps.model.DTO.req.PestUpdateRequestDTO;
import info.douyi.dps.model.DTO.resp.PestFrontResponseDTO;
import info.douyi.dps.service.InfluenceService;
import info.douyi.dps.service.PestService;
import info.douyi.dps.service.PreviewImgService;
import info.douyi.dps.service.QiniuService;
import info.douyi.dps.utils.PageResult;
import info.douyi.dps.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/Pest")
@CrossOrigin(origins = "*", allowCredentials = "false")
public class PestController {

    @Autowired
    private PestService pestService;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private PreviewImgService previewImgService;
    @Autowired
    private InfluenceService influenceService;

    @GetMapping("/getAllPest")
    public Result<List<Pest>> getAllPest() {
        List<Pest> pests = pestService.getAllPest();
        return Result.success(pests);
    }

    @GetMapping("/getPestByPage/{page}")
    public Result<PageResult<Pest>> getPestByPage(@PathVariable int page,  @RequestParam(defaultValue = "10") int size) {
        Result.success(PageResult.of(pestService.getPestByPage(page, size)));
        return Result.success(PageResult.of(pestService.getPestByPage(page, size)));
    }

    /**
     * 通过分类id获取该分类下的所有病虫害信息
     * @param bid
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getPestByBidWithPage/{bid}")
    public Result<PageResult<PestFrontResponseDTO>> getPestByBidWithPage(@PathVariable int bid, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        return Result.success(PageResult.of(pestService.getPestByPageByBid(bid,pageNum,pageSize)));
    }

    @GetMapping("/getPestByBidAndPtype1WithPage/{bid}")
    public Result<PageResult<Pest>> getPestByBidAndPtype1WithPage(@PathVariable int bid,@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        return Result.success(PageResult.of((pestService.getPestByPageByBidAndPType(bid,1,pageNum,pageSize))));
    }

    @GetMapping("/getPestByBidAndPtype0WithPage/{bid}")
    public Result<PageResult<Pest>> getPestByBidAndPtype0WithPage(@PathVariable int bid, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {
        return Result.success(PageResult.of((pestService.getPestByPageByBidAndPType(bid,0,pageNum,pageSize))));
    }

    @GetMapping("/getPestById")
    public Result<Pest> getPestById(@RequestParam int id) {
        PestWithBLOBs pestWithBLOBs= pestService.getPestWithBLOBs(id);
        if(pestWithBLOBs!=null){
            return Result.success(pestWithBLOBs);
        }else {
            return Result.error(0,"不存在该数据");
        }
    }

    @PostMapping(value="/insertPest" ,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<Pest> insertPest(@RequestPart("pest") PestInsertRequestDTO pestDTO,
                                   @RequestPart(value = "file", required = false) MultipartFile file) {
        PestWithBLOBs pest = new PestWithBLOBs();

        pest.setNamezhcn(pestDTO.getNameZHCN());
        pest.setNameeng(pestDTO.getNameEng());
        pest.setSynonyms(pestDTO.getSynonyms());
        pest.setIntroduction(pestDTO.getIntroduction());
        pest.setDamagesym(pestDTO.getDamageSym());
        pest.setPathogen(pestDTO.getPathogen());
        pest.setCycle(pestDTO.getCycle());
        pest.setOfactor(pestDTO.getOFactor());
        pest.setMorphology(pestDTO.getMorphology());
        pest.setHabits(pestDTO.getHabits());
        pest.setCmethod(pestDTO.getCMethod());
        pest.setPtype(pestDTO.getPtype());
        // 处理图片
        if (file != null && !file.isEmpty()) {
            try{
                pest.setOneimg(qiniuService.saveImage(file));
            }catch (Exception e){
                return Result.error(0,"图片上传失败");
            }
        } else {
            System.out.println("没有图片上传");
        }

        Pest insertPest = pestService.insertPest(pest);

        //插入病虫害之后，如果有图片，也插入图片表
        Integer pid = pest.getPid();
        System.out.println("插入的病虫害id为："+pid);

        if (pest.getOneimg() != null) {
            PreviewImg previewImg = new PreviewImg();
            previewImg.setPid(pid);
            previewImg.setImgurl(pest.getOneimg());
            previewImgService.addImage(previewImg);
            System.out.println("插入图片信息成功");
        }
        if(pestDTO.getBid() != null) {
            Influence influence = new Influence();
            influence.setBid(pestDTO.getBid());
            influence.setPid(pid);
            influenceService.addInfluence(influence);
        }

        if(insertPest!=null){
            return Result.success(insertPest);
        }else {
            return Result.error(0,"插入失败");
        }
    }

    //通过病虫害名称添加图片
    @PostMapping("/addImgByPestName")
    public Result<PreviewImg> addImgByPestName(@RequestParam("pestName") String pestName,
                                              @RequestPart("file") MultipartFile file) {
        PestExample example = new PestExample();
        example.createCriteria().andNamezhcnEqualTo(pestName);
        Pest pest = pestService.getPestByCNName(pestName);
        Integer pid = pest.getPid();

        if (file == null || file.isEmpty()) {
            return Result.error(0, "文件不能为空");
        }

        String fileUrl;
        try {
            fileUrl = qiniuService.saveImage(file);
        } catch (Exception e) {
            return Result.error(0, "图片上传失败");
        }

        PreviewImg previewImg = new PreviewImg();
        previewImg.setPid(pid);
        previewImg.setImgurl("https://"+fileUrl);
        int addedImg = previewImgService.addImage(previewImg);

        if(addedImg==0){
            return Result.success(previewImg);
        }else {
            return Result.error(0,"插入失败");
        }
    }

    //删除病虫害通过病虫害名称
    @DeleteMapping("/deletePestByName")
    public Result deletePestByName(@RequestParam("pestName") String pestName) {
        Pest pest = pestService.getPestByCNName(pestName);
        if (pest == null) {
            return Result.error(0, "未找到该病虫害");
        }
        Integer pid = pest.getPid();
        int deletedCount = pestService.deletePestById(pid);
        //TODO 级联删除其他表中的数据
        if (deletedCount > 0) {
            return Result.success("成功删除 " + deletedCount + " 条记录");
        } else {
            return Result.error(0, "删除失败");
        }
    }

    //通过病虫害中文名展示病虫害信息
    @GetMapping("/getPestByName")
    public Result<Pest> getPestByName(@RequestParam("pestName") String pestName) {
        Pest pest = pestService.getPestByCNName(pestName);
        if (pest != null) {
            return Result.success(pest);
        } else {
            return Result.error(0, "未找到该病虫害");
        }
    }

    //修改病虫害信息
    @PutMapping(value = "/updatePest")
    public Result<Pest> updatePest(@RequestBody PestUpdateRequestDTO pestUpdateDTO) {
        // 校验必要字段
        if (pestUpdateDTO.getPid() == null) {
            return Result.error(0, "PID 不能为空");
        }

        // 转换为数据库实体
        PestWithBLOBs pest = new PestWithBLOBs();
        pest.setPid(pestUpdateDTO.getPid());
        pest.setNamezhcn(pestUpdateDTO.getNameZHCN());
        pest.setNameeng(pestUpdateDTO.getNameEng());
        pest.setSynonyms(pestUpdateDTO.getSynonyms());
        pest.setIntroduction(pestUpdateDTO.getIntroduction());
        pest.setDamagesym(pestUpdateDTO.getDamageSym());
        pest.setPathogen(pestUpdateDTO.getPathogen());
        pest.setCycle(pestUpdateDTO.getCycle());
        pest.setOfactor(pestUpdateDTO.getOFactor());
        pest.setMorphology(pestUpdateDTO.getMorphology());
        pest.setHabits(pestUpdateDTO.getHabits());
        pest.setCmethod(pestUpdateDTO.getCMethod());
        pest.setPtype(pestUpdateDTO.getPtype());

        // 传 pest 实体给 service，不是 DTO！
        int updatedCount = pestService.updatePest(pest); // ← 关键修复！

        if (updatedCount > 0) {
            return Result.success(pest);
        } else {
            return Result.error(0, "更新失败");
        }
    }
}
